<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/5/3
 * Time: 14:06
 */
namespace app\first\model;

use app\admin\model\Pic;
use think\db\Where;
use think\Model;

class Dream extends Model {
    protected $autoWriteTimestamp = false;
    /**
     * @param array $where
     * @param string $order
     * @param int $limit
     * @param string $filed
     * @param bool $out
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where=[],$order='create_time desc',$limit=10,$filed='*',$out=false){
        $list = $this
            ->field($filed,$out)
            ->with(['user'=>function($query){
                $query->field('id,account,nickname,sex,avatar,is_auth,is_vip,vip_type');
            }])
            ->where($where)
            ->order($order)
            ->paginate($limit);
//        foreach ($list as $k => &$v){
//            $v['message'] = $message->where('aid','eq',$v['id'])->count();
//            $v['collection'] = $collection->where('aid','eq',$v['id'])->count();
//        }
        return $list;
    }

    /**
     * @param int $mid
     * @param string $title
     * @param string $image
     * @param string $content
     * @param string $location
     * @param string $address
     * @param int $city_id
     * @param string $out
     * @return bool
     */
    public function addNew($mid=0,$title='',$image='',$content='',$location='',$address='',$city_id=0,&$out=''){
        $data = [
            'mid'=>$mid,
            'title'=>$title,
            'image'=>$image,
            'content'=>$content,
            'location'=>$location,
            'address'=>$address,
            'city_id'=>$city_id,
            'status'=>1,
            'create_time'=>time(),
        ];
        $valid = new \app\first\validate\Dream();
        if(!$valid->check($data)){
            $out = $valid->getError();
            return false;
        }
//        $count = $this->where('title','eq',$title)->count('1');
//        if($count){
//            $out = '存在一个类似的梦想';
//            return false;
//        }
        if(!$this->save($data)){
            $out = '发布失败';
            return false;
        }
        return true;
    }
    /**
     * @param $q
     * @param $where
     * @param $limit
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function search($q,$where,$limit){
//        $list = $this
//            ->field('id,content,create_time')
//            ->where($where)
//            ->whereRaw("match(content) against('+{$q}' in boolean mode)")
//            ->paginate($limit);
        $list = $this
            ->field('id,content,create_time')
            ->where($where)
            ->whereLike('content',"%$q%")
            ->paginate($limit);
//        foreach ($list as &$v){
//            if($v['cid_type']==3){
//                $v['content'] = $this->getFieldById($v['id'],'content');
//            }else{
//                $v['content'] = '';
//            }
//        }
        return $list;
    }


    /**
     * @param int $cate_id
     * @param int $city_id
     * @param string $order
     * @param int $limit
     * @param string $filed
     * @param bool $out
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lastList($city_id=0,$order='create_time desc',$limit=10,$filed='*',$out=false){
        $where = new Where;
        $where['status']=2;
        if($city_id){
            $where['city_id']=$city_id;
        }
        $list = $this
            ->field($filed,$out)
            ->with(['user'=>function($query){
                $query->field('id,account,nickname,sex,avatar,is_auth,is_vip,vip_type');
            }])
            ->where($where)
            ->order($order)
            ->limit($limit)
            ->select();
        return $list;
    }

    /**
     * @param int $id
     * @param string $filed
     * @return array|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOneById($id=0,$filed=''){
        $filed = $filed?$filed:'update_time';
        $info = $this->field($filed,true)->find($id);
        $info->hits = $info['hits'] + 1;
        $info->save();
        $res = $this
            ->with(['user'=>function($query){
                $query->field('id,account,nickname,sex,avatar,is_auth,is_vip,vip_type');
            }])
            ->where('id','eq',$id)
            ->find();
        return $res;
    }

    /**
     * @param $id
     * @return array|mixed|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function memberByDreamId($id){
        $info = $this->field('id,mid')->find($id);
        if(!$info){
            return [];
        }
        $member = new Member();
        $info = $member->find($info['mid']);
        return $info;
    }

    /**
     * @param $cid
     * @param int $limit
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function likes($cid,$limit=4){
        $_limit = $limit * 5;
        $sql = "SELECT t1.id,t1.title,t1.image,t1.create_time FROM `{$this->getTable()}` AS t1 
          JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `{$this->getTable()}`)-(SELECT MIN(id) 
          FROM `{$this->getTable()}`))+(SELECT MIN(id) FROM `{$this->getTable()}`)) AS id from `{$this->getTable()}` limit {$_limit}) AS 
          t2 on t1.id=t2.id where t1.twice_cate_id = {$cid} and t1.status = 2 ORDER BY t1.id LIMIT {$limit}";
        $list = $this->query($sql);
        return $list;
    }

    public function user(){
        return $this->hasOne('member','id','mid');
    }

    /**
     * @param $value
     * @return array|bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getImageAttr($value){
        if(empty($value)){
            return '';
        }
        $pic = new Pic();
        return $pic->getUrlsById(explode(',',$value));
    }

    /**
     * @param $value
     * @return string
     */
    public function setContentAttr($value){
        if($value){
            return htmlspecialchars($value);
        }else{
            return '';
        }
    }

    /**
     * @param $value
     * @return string
     */
    public function getContentAttr($value){
        if($value){
            return htmlspecialchars_decode($value);
        }else{
            return '';
        }
    }
}